/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of The Qt Company Ltd nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "browser.h"
#include "browserwindow.h"
#include "downloadmanagerwidget.h"
#include "tabwidget.h"
#include "webview.h"
#include <QApplication>
#include <QCloseEvent>
#include <QDesktopWidget>
#include <QEvent>
#include <QFileDialog>
#include <QInputDialog>
#include <QMenuBar>
#include <QMessageBox>
#include <QProgressBar>
#include <QScreen>
#include <QStatusBar>
#include <QToolBar>
#include <QVBoxLayout>
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
#include <QWebEngineFindTextResult>
#endif
#include <QWebEngineProfile>
#include <QTimer>

BrowserWindow::BrowserWindow(Browser *browser, QWebEngineProfile *profile,  QString vkm_link, bool forDevTools)
    : m_browser(browser)
    , m_profile(profile)
    , m_homeLink(vkm_link)
    , m_tabWidget(new TabWidget(profile, this))
{
    setFocusPolicy(Qt::ClickFocus);

    setWindowTitle(tr("MVKM"));

    m_windowSize = QSize( settings.value("windowSize/width", QApplication::desktop()->screenGeometry().width()).toInt(), settings.value("windowSize/height", QApplication::desktop()->screenGeometry().height()).toInt());
    m_windowPos  = QPoint( settings.value("windowPos/x", 0).toInt(), settings.value("windowPos/y", 0).toInt());
    this->setGeometry(QRect(m_windowPos, m_windowSize));

    /////////////SetTrayMenu/////////////

    m_appTrayIcon = new QSystemTrayIcon( this );
    m_appTrayIcon->setToolTip(tr("Open MVKM"));
    m_appTrayIcon->setIcon(QIcon(":/mos-vkm.png"));

    // Set Tray Icon Context Menu
    QMenu* tray_menu = new QMenu(this);

    QAction* closeAppAction = new QAction(tr("Quit MVK Messenger"), this);
    connect(closeAppAction, SIGNAL(triggered()), this, SLOT(close()));
    tray_menu->addAction(closeAppAction);

    connect(m_appTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconActivation()));

    m_appTrayIcon->setContextMenu(tray_menu);
    m_appTrayIcon->show();
    /////////////////////////////////////

    //////////////SetMenuBar/////////////

    QMenu *appMenu = new QMenu(tr("App"));
    QAction *reloadAction = appMenu->addAction(tr("Reload"));
    connect(reloadAction, &QAction::triggered, this, &BrowserWindow::reload);

    QAction *homeAction = appMenu->addAction(tr("Return home page"));
    connect(homeAction, &QAction::triggered, this, &BrowserWindow::home);

    QAction *closeAction = appMenu->addAction(tr("Close application"));
    connect(closeAction, &QAction::triggered, this, &BrowserWindow::close);

    menuBar()->addMenu(appMenu);

    /////////////////////////////////////

    QWidget *centralWidget = new QWidget(this);
    QVBoxLayout *layout = new QVBoxLayout;
    layout->setSpacing(0);
    layout->setContentsMargins(0, 0, 0, 0);

    layout->addWidget(m_tabWidget);
    centralWidget->setLayout(layout);
    setCentralWidget(centralWidget);
    m_tabWidget->createTab();

    //////////////SetjQuery//////////////

    QFile file;
    file.setFileName(":/libs/jQuery/jquery.min.js");
    file.open(QIODevice::ReadOnly);
    jQuery = file.readAll();
    jQuery.append("\nvar qt = { 'jQuery': jQuery.noConflict(true) };");
    file.close();

    connect(m_tabWidget->currentWebView(), &QWebEngineView::loadFinished, this, &BrowserWindow::finishLoading);
    /////////////////////////////////////
}

QSize BrowserWindow::sizeHint() const
{
    QRect desktopRect = QApplication::primaryScreen()->geometry();
    QSize size = desktopRect.size() * qreal(0.9);
    return size;
}

TabWidget *BrowserWindow::tabWidget() const
{
    return m_tabWidget;
}

WebView *BrowserWindow::currentTab() const
{
    return m_tabWidget->currentWebView();
}

void BrowserWindow::close()
{
    exit(0);
}

void BrowserWindow::reload()
{
    m_tabWidget->currentWebView()->reload();
}

void BrowserWindow::home()
{
    QUrl vkm_url = QUrl(m_homeLink);
    m_tabWidget->currentWebView()->setUrl(vkm_url);
}

void BrowserWindow::trayIconActivation()
{
    if (this->isVisible())
    {
        this->hide();
    } else
    {
        this->setGeometry(QRect(m_windowPos, m_windowSize));
        this->show();
    }
}

void BrowserWindow::finishLoading(bool)
{
    m_tabWidget->currentWebView()->page()->runJavaScript(jQuery);
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(setButtons()));
    timer->start(100);
}

void BrowserWindow::setButtons()
{
    QString code;



    code = QStringLiteral("var selectColor = 'rgb(245, 246, 247)'; qt.jQuery('.MEApp__route').each(function() {"
                           "if(qt.jQuery('.MEApp__route').css('background-color') == 'rgb(25, 25, 26)'){selectColor = 'rgb(34, 34, 35)'}"
                           "});");
    code += QStringLiteral("qt.jQuery('.ActionsMenu').each(function() {"
                          "if(qt.jQuery(this).css('background-color') != 'var(--vkui--color_background_content)'){"
                           "qt.jQuery(this).css('background-color', 'var(--vkui--color_background_content)');  qt.jQuery(this).css('width', '260');  "
                           "qt.jQuery(this).css('border-style', 'solid'); qt.jQuery(this).css('border-radius', '10px'); qt.jQuery(this).css('border-width', '0.5'); qt.jQuery(this).css('border-color', 'var(--vkui--color_transparent--active)');"
                           "}});");
    code += QStringLiteral("qt.jQuery('.ActionsMenuAction').each( function () { "
                          "qt.jQuery(this).css('display', 'inline-flex');"
                          "}); ");
    code += QStringLiteral("qt.jQuery('.ActionsMenuAction').each(function() {"
                           "if(qt.jQuery(this).css('background-color') == 'rgb(239, 239, 239)'){"
                           "qt.jQuery(this).css('background-color', 'var(--vkui--color_background_content)'); qt.jQuery(this).css('color', 'var(--vkui--color_text_primary)');  "
                           "qt.jQuery(this).css('width', '260'); qt.jQuery(this).css('height', '32'); qt.jQuery(this).css('border', 'none'); qt.jQuery(this).css('display', 'list-item'); qt.jQuery(this).css('text-align', 'left'); qt.jQuery(this).css('vertical-align', 'middle');"

                           "qt.jQuery('.ActionsMenuAction__icon').each( function (){"
                           "qt.jQuery(this).css('align-items', 'center');"
                           "}); "

                           "qt.jQuery('.ActionsMenuAction__title').each( function (){"
                           "qt.jQuery(this).css('margin-left', '10px'); qt.jQuery(this).css('font', '400 var(--messageActionsMenuTitleFontSize) /var(--messageActionsMenuTitleLineHeight) var(--font)');"
                           "}); "

                           "}"
                           "});");
    code += QStringLiteral("qt.jQuery('.ActionsMenuAction').closest('button').hover( function () { "
                           "qt.jQuery(this).css('background-color', selectColor)}, function () { qt.jQuery(this).css('background-color', 'var(--vkui--color_background_content)')"
                           "}); ");
    code += QStringLiteral("qt.jQuery('.RightPanel__container').each( function () { "
                          "qt.jQuery(this).css('background-color', 'var(--vkui--color_background_content)');"
                          "}); ");

    code += QStringLiteral("qt.jQuery('.RightPanelContainer__mainContent').each( function () { "
                          "qt.jQuery(this).css('width', 'calc(100% - var(--compress_width))');"
                          "}); ");
    code += QStringLiteral("qt.jQuery('.RE_ModalHeader').each( function () { "
                           "qt.jQuery(this).css('background-color', 'var(--vkui--color_background_tertiary)'); qt.jQuery(this).css('border-bottom', '1px solid var(--vkui--color_separator_secondary)'); qt.jQuery(this).css('height', '54px'); qt.jQuery(this).css('font', '14px/16px var(--font)');"
                           "}); ");
    code += QStringLiteral("qt.jQuery('.RE_ModalPanel').each( function () { "
                          "qt.jQuery(this).css('background', 'var(--vkui--color_background_modal)'); qt.jQuery(this).css('border-radius', '8px'); qt.jQuery(this).css('display', 'grid');"
                           "qt.jQuery(this).css('grid-auto-rows', 'auto 1fr auto');"
                          "}); ");
    code += QStringLiteral("qt.jQuery('.RE_ModalHeader__title').each( function () { "
                          "qt.jQuery(this).css('padding-left', '15px');"
                          "}); ");
    code += QStringLiteral("qt.jQuery('.ImportantMessagesList').each( function () { "
                          "qt.jQuery(this).css('width', '610px');"
                          "}); ");
    code += QStringLiteral("qt.jQuery('button').each( function () { "
                          "qt.jQuery(this).css('outline', '0');"
                          "}); ");

    code += QStringLiteral("qt.jQuery('.ConvoList__item').each( function () { "
                           "qt.jQuery(this).css('width', '95%');"
                           "}); ");
    code += QStringLiteral("qt.jQuery('a[href=\"https://sferum.ru/?s=me\"]').each( function () { "
                           "qt.jQuery(this).css('color', 'rgb(82, 158, 244)');"
                           "}); ");
    code += QStringLiteral("qt.jQuery('button > span:contains(\"Enter\")').closest('button').each( function () { "
                           "qt.jQuery(this).css('height', '120%');"
                           "}); ");
    code += QStringLiteral("qt.jQuery('.MessageActionsDropdown--closed').each( function () { "
                               "qt.jQuery(this).removeClass('MessageActionsDropdown--closed');"
                               "qt.jQuery(this).addClass('MessageActionsDropdown--opened');"
                               "}); ");

    m_tabWidget->currentWebView()->page()->runJavaScript(code);
}

void BrowserWindow::resizeEvent (QResizeEvent * event)
{
    m_windowSize = this->size();
    settings.setValue("windowSize/width", m_windowSize.width());
    settings.setValue("windowSize/height", m_windowSize.height());
}

void BrowserWindow::changeEvent(QEvent *event)
{
    m_windowPos = this->pos();
    QTimer::singleShot(200, this, [this]{
        settings.setValue("windowPos/x", m_windowPos.x());
        settings.setValue("windowPos/y", m_windowPos.y());
    });
}

BrowserWindow::~BrowserWindow()
{
    deleteLater();
    delete m_appTrayIcon;
}
